require('dotenv').config();
const express = require('express');
const cors = require('cors');
const adminMessageRoutes = require('./routes/adminMessages');
const userMessageRoutes = require('./routes/userMessages');
const errorHandler = require('./middleware/errorHandler');
const { authenticateToken } = require('./middleware/authMiddleware'); // If globally applied

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
app.use(cors({
  origin: '*',
  credentials: true,
  allowedHeaders: ['Content-Type', 'X-User-ID','X-User-Role']
}));

app.use(authenticateToken);

app.get('/', (req, res) => {
  res.send('Message Notification System API is running!');
});

app.use('/api/admin/messages', adminMessageRoutes);
app.use('/api/messages', userMessageRoutes);

// Centralized Error Handler - MUST be last, after all routes and other middleware
app.use(errorHandler);

// Start server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  // Test DB connection (optional)
  const db = require('./config/db');
  db.query('SELECT NOW()', (err, res) => {
    if (err) {
      console.error("Failed to connect to DB on startup:", err);
    } else {
      // console.log("DB connection test successful:", res.rows[0]);
    }
  });
});
